<template>
  <div class="admin-countries">
    <div class="header flex justify-between items-center mb-4">
      <el-button type="primary" @click="dialogVisible = true">
        新增国家
      </el-button>
    </div>
    <!-- 搜索表单 -->
    <el-form
      ref="searchFormRef"
      :model="searchForm"
      inline
      class="search-form mb-4"
    >
      <el-form-item label="来源" prop="source">
        <el-input
          v-model="searchForm.source"
          placeholder="请输入来源"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="onlyEnabled">
        <el-select
          v-model="searchForm.onlyEnabled"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 国家配置列表 -->
    <el-table
      :data="paginatedData"
      stripe
      border
      style="width: 100%"
      show-overflow-tooltip
    >
      <el-table-column label="排序" width="180">
        <template #default="scope">
          <el-input
            v-model.number="scope.row.sortOrder"
            size="small"
            style="width: 80px"
          />
          <el-button
            type="primary"
            size="small"
            style="margin-left: 5px"
            @click="updateSortOrder(scope.row)"
          >
            更新
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" />
      <el-table-column prop="name" label="国家名称" />
      <el-table-column label="启用状态">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'info'">
            {{ scope.row.enabled ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="220">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            link
            @click="editCountryName(scope.row)"
            >修改名称</el-button
          >
          <el-popconfirm
            width="220"
            :icon="InfoFilled"
            icon-color="#626AEF"
            :title="`确定${scope.row.enabled ? '禁用' : '启用'}该国家吗？`"
            @confirm="confirmStatus(scope.row)"
          >
            <template #reference>
              <el-button
                link
                :type="scope.row.enabled ? 'danger' : 'success'"
                size="small"
              >
                {{ scope.row.enabled ? "禁用" : "启用" }}
              </el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="confirm">
                确定
              </el-button>
            </template>
          </el-popconfirm>
          <el-button
            type="danger"
            size="small"
            link
            @click="deleteCountry(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      class="mt-4"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableData.length"
      :page-sizes="[10, 20, 50]"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 新增/编辑国家对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增国家配置"
      width="500px"
      @close="close"
    >
      <el-form
        ref="countryFormRef"
        :model="countryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="展示名称" prop="displayName">
          <el-input
            v-model="countryForm.displayName"
            placeholder="请输入展示名称"
          />
        </el-form-item>
        <el-form-item label="国际区号" prop="countryCode">
          <el-input
            v-model="countryForm.countryCode"
            placeholder="国际区号，如+86"
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="enabled">
          <el-switch
            v-model="countryForm.enabled"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCountry">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { InfoFilled } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import {
  getAllCountries,
  createCustomCountry,
  updateCountrySortOrder,
  updateCountryDisplayName,
  updateCountryEnabled,
  deleteCustomCountry
} from "@/api/adminCountryApi";

// 搜索表单数据
const searchForm = reactive({
  source: "",
  onlyEnabled: ""
});
const searchFormRef = ref();

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 表格数据
const tableData = ref<any[]>([]);

// 分页显示的数据
const paginatedData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  return tableData.value.slice(start, start + pagination.pageSize);
});

// 获取所有国家配置数据
const fetchCountries = async () => {
  try {
    const res = await getAllCountries(searchForm);
    if (res && res.success) {
      tableData.value = res.data;
      pagination.total = res.data.length;
    } else {
      ElMessage.error(res?.message || "获取国家配置失败");
    }
  } catch (error) {
    ElMessage.error("请求国家配置数据失败");
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchCountries();
};

const onReset = () => {
  searchForm.source = "";
  searchForm.onlyEnabled = "";
  pagination.currentPage = 1;
  fetchCountries();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
};

// 新增/编辑对话框相关
const dialogVisible = ref(false);
const countryForm = reactive({
  countryCode: "",
  displayName: "",
  enabled: true
});
const countryFormRef = ref<FormInstance>();

const rules: FormRules = {
  displayName: [{ required: true, message: "请输入展示名称", trigger: "blur" }]
};

// 新增国家
const close = () => {
  countryFormRef.value?.resetFields();
  countryFormRef.value?.clearValidate();
};

// 提交新增
const submitCountry = async () => {
  countryFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        const { countryCode, displayName, enabled } = countryForm;
        await createCustomCountry({
          countryCode,
          displayName,
          enabled
        });
        ElMessage.success("新增国家配置成功");
        dialogVisible.value = false;
        fetchCountries();
      } catch (error) {
        ElMessage.error("提交失败");
      }
    }
  });
};

// 删除国家配置
const deleteCountry = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定删除国家配置【${row.name}】吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    await deleteCustomCountry(row.id);
    ElMessage.success("删除成功");
    fetchCountries();
  } catch (error) {
    ElMessage.info("已取消删除");
  }
};

// 更新排序操作
const updateSortOrder = async (row: any) => {
  try {
    await updateCountrySortOrder(row.id, row.sortOrder);
    ElMessage.success("更新排序成功");
    fetchCountries();
  } catch (error) {
    ElMessage.error("更新排序失败");
  }
};

// 更新国家启用状态
const confirmStatus = async (row: any) => {
  try {
    await updateCountryEnabled(row.id, !row.enabled);
    ElMessage.success("更新启用状态成功");
    fetchCountries();
  } catch (error) {
    ElMessage.error("更新启用状态失败");
  }
};

// 修改国家名称
const editCountryName = async (row: any) => {
  ElMessageBox.prompt("请输入新的国家名称", "修改国家名称", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputValue: row.displayName
  })
    .then(async ({ value }) => {
      if (value) {
        await updateCountryDisplayName(row.id, value);
        ElMessage.success("修改国家名称成功");
        fetchCountries();
      }
    })
    .catch(() => {});
};
onMounted(() => {
  fetchCountries();
});
</script>

<style scoped>
.admin-countries {
  padding: 20px;
  background-color: #fff;
}
.header h2 {
  font-size: 20px;
  font-weight: bold;
}
</style>
